#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 带有外部状态的生成器函数
问题: 你想定义一个生成器函数，但是它会调用某个你想暴露给用户使用的外部状态值
提示 : 
"""
from collections import deque

def recipe1():
    with open('../somefile.txt') as f:
        lines = linehistory(f)
        for line in lines:
            if 'Python' in line:
                for lineno, hline in lines.history:
                    print('{}:{}'.format(lineno, hline), end='')

def recipe2():
    """迭代操作时不使用for循环语句，那么你得先调用 iter() 函数"""
    f = open('../somefile.txt')
    lines = linehistory(f)
    # next(lines) # TypeError
    it = iter(lines)
    print(f"{next(it) = }")

class linehistory:
    def __init__(self, lines, hislen = 3) -> None:
        self.lines = lines
        self.history = deque(maxlen=hislen)

    def __iter__(self):
        for lineno, line in enumerate(self.lines, 1):
            self.history.append((lineno, line))
            yield line

    def clear(self):
        self.history.clear()

def main():
    print('recipe1'.center(20, '*'))
    recipe1() 
    print('recipe2'.center(20, '*'))
    recipe2() 

if __name__ == '__main__':
    main()          